<template>
  <div>
    <DragFileArea @addFile="addFile" />
    <UpdateFileList
      @addFile="addFile"
      @removeFile="removeFile"
      @updateFile="updateFileAll"
      :fileList="fileList"
    />
  </div>
</template>

<script lang="ts" setup>
import { postFileTable } from '@/api/IndexViewApi'
import DragFileArea from '@/components/IndexViewComp/DragFileArea.vue'
import UpdateFileList from '@/components/IndexViewComp/UpdateFileList.vue'
import { ref } from 'vue'

const fileList = ref([])

const addFile = (file) => {
  const item = {
    id: fileList.value.length,
    name: file.name,
    size: file.size,
    type: file.type,
    status: '待上传',
    process: 0,
    file: file
  }
  fileList.value.push(item)
}

const updateFileAll = async () => {
  for (let i = 0; i < fileList.value.length; i++) {
    const fileObj = fileList.value[i]
    if (fileObj.status === '待上传') {
      updateFile(fileObj)
    }
  }
}

const updateFile = async (fileObj) => {
  const formData = new FormData()
  const time = new Date().getTime()
  formData.append('files.file', fileObj.file, `${time}`)
  formData.append(
    'data',
    JSON.stringify({
      name: fileObj.name,
      size: fileObj.size,
      type: fileObj.type
    })
  )

  try {
    await postFileTable(formData, fileObj)
    fileObj.status = '上传成功'
    fileObj.process = 100
  } catch (error) {
    fileObj.status = '上传失败'
  }
}

const removeFile = (index) => {
  fileList.value.splice(index, 1)
}
</script>

<style lang="scss" scoped></style>
